<template>
  <view class="goods-detail-container" v-if="goods_info.goods_name">
    <!-- 轮播图区域 -->
    <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
      <swiper-item v-if="goods_info.pics" v-for="(item,i) in goods_info.pics" :key="i">
        <image :src="getImageSrc(item)" @click="preview(i)"></image>
      </swiper-item>
    </swiper>

    <!-- 商品详情 -->
    <view class="goods-info-box">
      <!-- 价格 -->
      <view class="price">￥{{goods_info.goods_price}}</view>
      <!-- 详情主体 -->
      <view class="goods-info-body">
        <!-- 介绍 -->
        <view class="goods-name">
          {{goods_info.goods_name}}
        </view>
        <!-- 图标 -->
        <view class="favl">
          <uni-icons type="star" size="17"></uni-icons>
          <text>收藏</text>

        </view>
      </view>
      <!-- 快递 -->
      <view class="yf">快递：免运费</view>

      <!-- <rich-text :nodes="getIntroduce(this.goods_info.goods_introduce)"></rich-text> -->
      <rich-text :nodes="goods_info.goods_introduce"></rich-text>
    </view>
    <!-- 商品组件 -->
    <view class="goods-nav">
      <uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
        @buttonClick="buttonClick" />
    </view>

  </view>
</template>

<script>
  import {
    handleError
  } from 'vue';
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    data() {
      return {
        // 商品详情
        goods_info: {},
        defaultPic: 'https://ts1.cn.mm.bing.net/th/id/R-C.c187d181f69fdaeabe305ff7dc703817?rik=gb8yxqTJ5Xq5FQ&riu=http%3a%2f%2fpic.616pic.com%2fys_bnew_img%2f00%2f58%2f20%2f7iAcTfJhSA.jpg&ehk=DpREV5w4rqsBi5LE172coTqWDRIhtBwp0z1aDC69vLc%3d&risl=&pid=ImgRaw&r=0',
        options: [{
          icon: 'shop',
          text: '店铺',
          infoBackgroundColor: '#007aff',
          infoColor: "red"
        }, {
          icon: 'cart',
          text: '购物车',
          info: 0
        }],
        buttonGroup: [{
            text: '加入购物车',
            backgroundColor: '#ff0000',
            color: '#fff'
          },
          {
            text: '立即购买',
            backgroundColor: '#ffa200',
            color: '#fff'
          }
        ]
      };
    },
    onLoad(options) {
      // console.log(options)
      this.getGoodsInfo(options.goods_id)
    },
    methods: {
      ...mapMutations('m_cart', ['addToCart']),
      async fetchDataSrcValues(html) {
        // const regex = /data-src="(.*?)"/g; // 将 regex 定义放在函数内部 
        const regex1 = /src="(.*?)"/g;
        let match;
        let updatedHtml = html; // 新字符串，用于存储更新后的 HTML

        // while ((match = regex.exec(html)) !== null) {
        //   const url = match[1];
        //   // 检测 URL 是否有效
        //   try {
        //     const response = await fetch(url, {
        //       method: 'HEAD'
        //     }); // 使用 HEAD 请求来检测有效性
        //     if (response.ok) {
        //       validUrls.push(url); // 如果响应状态为 200-299，则认为链接有效
        //     } else {
        //       // console.log(`Invalid URL: ${url} (status: ${response.status})`);
        //       updatedHtml = updatedHtml.replace(url, this.defaultPic);
        //     }
        //   } catch (error) {
        //     // console.log(`Error fetching URL: ${url} (${error.message})`);

        //     updatedHtml = updatedHtml.replace(url, this.defaultPic);

        //   }
        // }
        while ((match = regex1.exec(html)) !== null) {
          const url = match[1];
          // 检测 URL 是否有效
          try {
            const response = await fetch(url, {
              method: 'HEAD'
            }); // 使用 HEAD 请求来检测有效性
            if (response.ok) {
              // validUrls.push(url); // 如果响应状态为 200-299，则认为链接有效
              return response.text().then(text => {
                // 如果返回的内容是错误信息，则视为无效 URL
                if (text.includes('error')) {
                  updatedHtml = updatedHtml.replace(url, this.defaultPic);
                } else {
                  validUrls.push(url); // 记录有效 URL
                }
              });
            } else {
              // console.log(`Invalid URL: ${url} (status: ${response.status})`);
              updatedHtml = updatedHtml.replace(url, this.defaultPic);
            }
          } catch (error) {
            // console.log(`Error fetching URL: ${url} (${error.message})`);

            updatedHtml = updatedHtml.replace(url, this.defaultPic);

          }
        }

        // console.log(updatedHtml)
        return updatedHtml;
      },
      getImageSrc(item) {
        // 根据 item 中的 pics_big 属性返回图片地址，若不存在则使用默认图片
        return item.pics_big ? item.pics_big : this.defaultPic;
      },

      async getGoodsInfo(goods_id) {
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/detail', {
          goods_id
        })
        if (res.meta.status !== 200) return uni.$showMsg()

        res.message.goods_introduce = res.message.goods_introduce.replace(/<img /g, '<img style="display: block;" ')
          .replace(/webp/g, 'jpg')
        // console.log(res.message.goods_introduce)
        // console.log(res.message.goods_introduce)
        // this.fetchDataSrcValues(res.message.goods_introduce).then(updatedHtml => {
        //   res.message.goods_introduce = updatedHtml
        //   console.log(res.message.goods_introduce)
        // });

        this.goods_info = res.message
        // console.log(this.goods_info)
      },
      preview(i) {
        uni.previewImage({
          current: i,
          urls: this.goods_info.pics.map(x => x.pics_big)
        })
      },
      onClick(e) {
        console.log(e)
        if (e.content.text === '购物车') {
          uni.switchTab({
            url: '/pages/cart/cart',

          })
        }
      },
      buttonClick(e) {
        if (e.content.text === '加入购物车') {
          const goods = {
            goods_id: this.goods_info.goods_id,
            goods_name: this.goods_info.goods_name,
            goods_price: this.goods_info.goods_price,
            goods_count: 1,
            goods_small_logo: this.goods_info.goods_small_logo,
            goods_state: true,
          }
          this.addToCart(goods)
        }
      },

    },
    computed: {
      ...mapGetters('m_cart', ['total'])
    },
    watch: {
      total: {
        handler(newval) {
          const findResult = this.options.find((x) => x.text === '购物车')
          if (findResult) {
            findResult.info = newval
          }
        },
        immediate:true
      }
    }
  }
</script>

<style lang="scss">
  swiper {
    height: 750rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .goods-info-box {
    padding: 10px;
    padding-right: 0;

    .price {
      color: red;
      font-size: 18px;
      margin: 10px 0;
    }

    .goods-info-body {
      display: flex;
      justify-content: space-between;

      .goods-name {
        font-size: 13px;
        margin-right: 5px;
      }

      .favl {
        width: 120px;
        display: flex;
        flex-direction: column;
        font-size: 12px;
        align-items: center;
        justify-content: center;
        border-left: 1px solid #efefef;
        color: gray;
      }
    }

    .yf {
      font-size: 12px;
      color: gray;
      margin: 5px 0;

    }
  }

  .goods-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
  }

  .goods-detail-container {
    padding-bottom: 50px;
  }
</style>